var uuid = require('node-uuid');

var util = require('../../framework/util');
var logger = require('../../framework/util').logger('user.contrl');
var mongoose = require('../../framework/mongoose');
var service = require('./service');

var User =require('./model').User;

//Interface
exports.signonWithToken = function (req, res) {
    return User.findOne({token: req.body.token}).exec(function(err, obj){
        if(!err && obj != null){
            req.session.user = obj._id;
            res.send({code: 1, data: obj});
        } else {
            logger.info(err);
            res.send({code: 0, msg: 'Token is invalid.'});
        }
    });
};

exports.signon = function (req, res) {
    var vo = req.body;
    logger.info(vo);
    User.findOne({email: vo.email, passwd: vo.password}).exec(function(err, obj){

        if(!err && obj != null){   // found

            obj.token = uuid.v4();
            obj.updateTime = new Date();
            obj.save(function(){
                req.session.user = obj._id;
                res.send({code: 1, data: obj});
            });
        } else {
            res.send({code: 0, msg: 'Email or password is invalid.'});
        }
    });
};


exports.signup = function (req, res) {
    var vo = req.body;
    if (util.isEmpty(vo.email)) {
        var msg = 'Not a valid email.';
        var data = {code: 0, msg:msg};
        res.send(data);
    }
    User.findOne({email: vo.email}).exec(function(err, obj){
        if(!err && obj == null){   // not exist
            var user = new User({
                email:  vo.email,
                passwd: vo.password,
                token: uuid.v4(),
                phone: '',
                im: '',
                status: 1,
                createTime: new Date()
            });
            User.create(user, function (err, user) {
                req.session.user = user._id;
                res.send({code:1, data: user});
            });
        } else {
            res.send({code: 0, msg: 'Email already exists.'});
        }

    });
};

exports.signout = function (req, res) {
    req.session.user = null;
    res.send({code: 1});
};